package org.jash.user.login

import org.jash.user.util.FingerprintHelper
import androidx.fragment.app.FragmentActivity

import com.example.common.mvi.BaseActivity
import androidx.activity.viewModels
import org.jash.user.databinding.ActivityLoginBinding
import com.alibaba.android.arouter.facade.annotation.Route
import android.widget.Toast
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContracts
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import org.jash.user.R
import org.jash.user.register.RegisterActivity
import android.os.SystemClock

@Route(path = "/user/LoginActivity")

class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel, LoginIntent, LoginViewState>() {
	private val registerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
		if (result.resultCode == RESULT_OK) {
			val data = result.data
			val username = data?.getStringExtra("username") ?: ""
			val password = data?.getStringExtra("password") ?: ""
			binding.etPhone.setText(username)
			binding.etPassword.setText(password)
		}
	}

	// 防抖变量：记录上一次点击的时间戳
	private var lastClickTime: Long = 0
	// 防抖变量：设置点击间隔时间（毫秒），1000ms内不能重复点击
	private val CLICK_DELAY_TIME: Long = 1000

	override val viewModel: LoginViewModel by viewModels {
		object : androidx.lifecycle.ViewModelProvider.Factory {
			override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
				return LoginViewModel(LoginRepository()) as T
			}
		}
	}

	override fun getLayoutId(): Int = R.layout.activity_login

	// 防抖检查函数：检查是否可以响应点击事件
	private fun isClickAllowed(): Boolean {
		val currentTime = SystemClock.elapsedRealtime()
		if (currentTime - lastClickTime < CLICK_DELAY_TIME) {
			// 时间间隔小于设定值，不允许点击
			return false
		}
		// 更新上次点击时间为当前时间
		lastClickTime = currentTime
		return true
	}

	override fun setupViews() {
		// 自动填充用户名和密码（优先intent参数，其次sp）
		val username = SPUtils.getInstance().getString("username")
		val password = SPUtils.getInstance().getString("password")
		binding.etPhone.setText(username)
		binding.etPassword.setText(password)

		binding.ivBack.setOnClickListener { finish() }
		binding.tvUserAgreement.setOnClickListener {
			ARouter.getInstance().build("/user/WebVieAwctivity").navigation()
		}
		binding.tvPrivacyPolicy.setOnClickListener {
			ARouter.getInstance().build("/user/WebViewYINSIActivity").navigation()
		}
		binding.btnLogin.setOnClickListener {
			// 防抖处理：防止重复点击登录按钮
			if (!isClickAllowed()) return@setOnClickListener

			val username = binding.etPhone.text?.toString()?.trim().orEmpty()
			val password = binding.etPassword.text?.toString()?.trim().orEmpty()
			if (!binding.cbAgree.isChecked) {
				Toast.makeText(this, "请先阅读并勾选同意《用户协议》和《隐私政策》", Toast.LENGTH_SHORT).show()
				return@setOnClickListener
			}
			if (username.isEmpty() || password.isEmpty()) {
				Toast.makeText(this, "请输入手机号和密码", Toast.LENGTH_SHORT).show()
				return@setOnClickListener
			}
			sendIntent(LoginIntent.Login(username, password))
		}
		binding.tvRegister.setOnClickListener {
			// 防抖处理：防止重复点击注册按钮
			if (!isClickAllowed()) return@setOnClickListener

			// ARouter 跳转获取 intent
			val intent = Intent(this, RegisterActivity::class.java)
			registerLauncher.launch(intent)
		}

		binding.btnFingerprint.setOnClickListener {
			// 防抖处理：防止重复点击指纹登录按钮
			if (!isClickAllowed()) return@setOnClickListener

			FingerprintHelper.showBiometricPrompt(this as FragmentActivity, onSuccess = {
				// 指纹验证成功后自动登录指定账号
				val username = "15568859280"
				val password = "aa7410"
				binding.etPhone.setText(username)
				binding.etPassword.setText(password)
				sendIntent(LoginIntent.Login(username, password))
				Toast.makeText(this, "指纹验证成功", Toast.LENGTH_SHORT).show()
			}, onError = {
				Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
			})
		}
		binding.tvForget.setOnClickListener {
			// 防抖处理：防止重复点击忘记密码按钮
			if (!isClickAllowed()) return@setOnClickListener

		}
	}

	override fun renderViewState(state: LoginViewState) {
		binding.btnLogin.isEnabled = !state.isLoading
		if (state.isLoading) {
			// 可根据需要显示加载中UI
		}
		if (state.isSuccess) {
			Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
			setResult(RESULT_OK)
			finish()
		}
		if (state.error != null) {
			Toast.makeText(this, state.error, Toast.LENGTH_LONG).show()
		}
	}


}
